package com.lht.admin.utils;

import org.joda.time.DateTime;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
public class SerialNumberUtils {

    public static final String TYPE_APPLY_NO = "apply_no";
    public static final String TYPE_ORDER_NO = "order_no";
    public static final String PAY_CHANNEL_SMALL_ROUTINE = "SMALL_ROUTINE";

    private static final int SERIAL_NUMBER_MAX_LENGTH = 24;
    private static final String NUMBERS_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERS = "0123456789";

    private static final Map<String, String> TYPE_MIDDLE_MAP;
    private static final Map<String, String> PAY_CHANNEL_MAP;

    static {
        TYPE_MIDDLE_MAP = new HashMap<String, String>();
        TYPE_MIDDLE_MAP.put(TYPE_APPLY_NO, "A");
        TYPE_MIDDLE_MAP.put(TYPE_ORDER_NO, "O");

        PAY_CHANNEL_MAP = new HashMap<String, String>();
        PAY_CHANNEL_MAP.put(PAY_CHANNEL_SMALL_ROUTINE.toLowerCase(), "1");
    }

    public static String generateNo(long userId, String type) {
        return generateNo(userId, type, null);
    }

    public static String generateNo(long userId, String type, String payChannel) {
        String middle = TYPE_MIDDLE_MAP.get(type);
        if (org.apache.commons.lang.StringUtils.isBlank(middle)) {
            throw new RuntimeException("type不能为空！");
        }
        StringBuilder no = new StringBuilder();
        no.append(middle);
        no.append(getStringDate());
        if (org.apache.commons.lang.StringUtils.isNotBlank(payChannel)) {
            String payChannelCode = PAY_CHANNEL_MAP.get(payChannel.toLowerCase());
            no.append(payChannelCode);
        }
        no.append(userId).append(getRandomNumChar(1));
        int surplusLength = SERIAL_NUMBER_MAX_LENGTH - no.length();
        return no.append(getRandomNum(surplusLength)).toString();
    }

    private static String getRandomNum(int length) {
        if (length <= 0) {
            throw new RuntimeException("length不能小于等于0！");
        }
        Random random = new Random();
        StringBuilder randomNum = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(NUMBERS.length());
            randomNum.append(NUMBERS.charAt(index));
        }
        return randomNum.toString();
    }

    private static String getRandomNumChar(int length) {
        if (length <= 0) {
            throw new RuntimeException("length不能小于等于0！");
        }
        Random random = new Random();
        StringBuilder randomNum = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(NUMBERS_CHARS.length());
            randomNum.append(NUMBERS_CHARS.charAt(index));
        }
        return randomNum.toString();
    }

    private static String getStringDate() {
        return DateTime.now().toString("yyMMdd");
    }
}
